package cn.xsly.org.service.impl;

import cn.xsly.basic.service.impl.BaseServiceImpl;
import cn.xsly.basic.util.Md5Utils;
import cn.xsly.basic.util.StrUtils;
import cn.xsly.org.domain.Employee;
import cn.xsly.org.mapper.EmployeeMapper;
import cn.xsly.org.service.EmployeeService;
import cn.xsly.user.domain.Logininfo;
import cn.xsly.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements EmployeeService {
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public void add(Employee employee) {
        //1.处理密码和盐值
        //获取随机盐值
        String salt = StrUtils.getComplexRandomString(32);
        //获取加密之后的密码
        String md5Pwd = Md5Utils.encrypByMd5(employee.getPassword() + salt);
        employee.setSalt(salt);
        employee.setPassword(md5Pwd);

        Logininfo logininfo = employee2Logininfo(employee);
        logininfoMapper.save(logininfo);

        employee.setLogininfo_id(logininfo.getId());
        employeeMapper.addEmployeeRole(employee);
        super.add(employee);
    }

    public Logininfo employee2Logininfo(Employee employee) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee, logininfo);
        //当前对象是店铺管理员
        logininfo.setType(0);
        return logininfo;
    }
    @Override
    public void del(Long id) {
        Employee employee = employeeMapper.loadById(id);
        employeeMapper.delEmployeeRoleByEmpId(id);

        //删除employee表数据
        super.del(id);
        //删除登录信息表数据
        logininfoMapper.remove(employee.getLogininfo_id());
    }
    @Override
    public void update(Employee employee){
        String salt=StrUtils.getComplexRandomString(32);
        employee.setSalt(salt);
        //密码 - 加盐加密之后的
        String md5Pwd = Md5Utils.encrypByMd5(employee.getPassword() + salt);
        employee.setPassword(md5Pwd);
        //先删除以前的中间数据
        employeeMapper.delEmployeeRoleByEmpId(employee.getId());
        //再添加新的数据
        employeeMapper.addEmployeeRole(employee);
        //2.修改员工信息
        super.update(employee);

        //3.修改logininfo信息：通过id【logininfo_Id】去修改
        Employee oldEmployee = employeeMapper.loadById(employee.getId());
        Logininfo oldLogininfo = logininfoMapper.loadById(oldEmployee.getLogininfo_id());
        //5个同名属性就是最新的数据
        BeanUtils.copyProperties(employee, oldLogininfo);
        logininfoMapper.update(oldLogininfo);
    }


}